import base64
import re
import os
import uuid
from pathlib import Path

def img_encode(file_path):
    """
    解析图片文件,用base64加密,返回加密后的文本信息
    :param file_path:
    :return:
    """
    # 1. 拓展名
    ext = file_path.split(".")[-1]
    # 2. 以二进制读取文件
    with open(file_path, "rb") as f:
        img = f.read()
    # 3. 使用base64加密
    data = base64.b64encode(img).decode()
    src = "data:image/{ext};base64,{data}".format(ext=ext, data=data)
    return src

def img_decode(src, file_path=None):
    """
    使用base64解密,生成图片文件,返回文件地址
    文件位置默认为根目录下的data/temp
    :param src:
    :param file_path:
    :return:
    """
    # 1、信息提取
    result = re.match("data:image/(?P<ext>.*?);base64,(?P<data>.*)", src, re.DOTALL)
    if result:
        ext = result.groupdict().get("ext")
        data = result.groupdict().get("data")
    else:
        raise Exception("Do not parse!")
    # 2、base64解码
    img = base64.urlsafe_b64decode(data)
    # 3、二进制文件保存
    file_path = os.sep + 'data' + os.sep + 'temp' if file_path is None else file_path
    with Path(file_path) as p:
        if p.is_dir():
            pass
        else:
            os.makedirs(file_path)
    filename = "{}{}{}.{}".format(file_path, os.sep, uuid.uuid1(), ext)
    with open(filename, "wb") as f:
        f.write(img)
    return filename

if __name__ == '__main__':
    src_temp = img_encode('19081610593570.jpeg')
    with open('text.txt', 'wt') as f:
        f.write(src_temp)

    with open('text.txt', 'r') as f_1:
        v_1 = f_1.read()
    print(img_decode(v_1))

    with open('temp.txt', 'r') as f_2:
        v_2 = f_2.read()
    print(img_decode(v_2))
